package com.yami.shop.listener;

import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.ObjectUtil;
import com.yami.shop.bean.event.CreateTreeImgEvent;
import com.yami.shop.bean.model.UserImg;
import com.yami.shop.common.util.FreemarkerUtil;
import com.yami.shop.service.AttachFileService;
import com.yami.shop.service.UserImgService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

@Slf4j
@Component("createTreeImgListener")
@AllArgsConstructor
public class CreateTreeImgListener {

    @Autowired
    private AttachFileService attachFileService;
    @Autowired
    private UserImgService userImgService;

    @EventListener(CreateTreeImgEvent.class)
    @Async
    public void createImg(CreateTreeImgEvent event) {
        log.info("HTML转图片***********************");
        try {
            MultipartFile multipartFile = FreemarkerUtil.html2ImgBase64(event.getHtml(), 2900, -1);
            UserImg byId = userImgService.getById(event.getOne().getId());
            // --- 异步处理 可能再等待时间 数据被删除 如果是空的话不传文件到minio
            if(ObjectUtil.isEmpty(byId)){
                log.info("HTML转图片---------------");
                return;
            }
            String sourceUrl = attachFileService.uploadFile(multipartFile.getBytes(), UUID.fastUUID() + ".png");
            log.info("HTML转图片完成================================");
            // 图片上传完成 修改数据
            event.getOne().setStatus("1");
            event.getOne().setSourceUrl(sourceUrl);
            userImgService.updateById(event.getOne());
        } catch (Exception e) {
            log.info("HTML转图片完成++++++++++++++++++++++++++++++{}", e);
        }
    }
}
